<?php
	include_once "config_db.php";
	$database = 'mymap';
	
	if (!mysql_connect($db_host, $db_user, $db_pwd))
	die("Can't connect to database");
		
	if (!mysql_select_db($database))
	die("Can't select database");
		
	mysql_query("SET NAMES 'utf8'");
	
	$i = 0;
	$j = 0;
	// load SimpleXML
	$name_document = "xml/map.xml";
	$xml = simplexml_load_file($name_document);
	$nodes = $xml->node;
	$ways = $xml->way;
	getNodes($nodes);
//	getWays($ways);
//	$file_name = $_REQUEST['path_and_file_name']; 
	function getWays($ways) {
		echo '
		<table>
		<tr>
		<th>STT</th>
		<th>ID</th>
		<th>List Node</th>
		<th>User</th>
		<th>Version</th>
		</tr>';
		foreach ($ways as $way) {
		    $id = $way->attributes()->id;		
		    $nds = $way->nd;
			$list_node = '';
			foreach ($nds as $nd) {
				$temp = $nd->attributes()->ref.", ";
				$list_node = $list_node.$temp;
			}	
			
		    $user = $way->attributes()->user;
		    
		    $version = $way->attributes()->version;
			echo '
				<tr>
				<td>'.$j.'</td>
				<td>'.$id.'</td>
				<td>'.$list_node.'</td>
				<td>'.$user.'</td>
				<td>'.$version.'</td>
				</tr>';
			$j++;
			if($j == 100){
				break;
			}
		}
		echo '</table>';
	}	
	
	function getNodes($nodes) {
		$stt = true;
//		echo '
//		<table>
//		<tr>
//		<th>STT</th>
//		<th>ID</th>
//		<th>Latitude</th>
//		<th>Longitude</th>
//		<th>User</th>
//		<th>Version</th>
//		</tr>';
		foreach ($nodes as $node) {
		    $id = $node->attributes()->id;
		    $lat = $node->attributes()->lat;
		    $lng = $node->attributes()->lon;
		    $version = $node->attributes()->version;
		    $result = insert_point($id, round_f($lat, 6), round_f($lng, 6), $version);
		    if($result){}
		    else {
		    	$stt = false;
		    	break;
		    }
		    
//			echo '
//				<tr>
//				<td>'.$i.'</td>
//				<td>'.$id.'</td>
//				<td>'.$lat.'</td>
//				<td>'.$lon.'</td>
//				<td>'.$user.'</td>
//				<td>'.$version.'</td>
//				</tr>';
		}
		if($stt) {
			echo 'Finish!';	
		} else {
			echo 'Error!';
		}
		
//		echo '</table>';
	}	
	function insert_point($id, $lat, $lng, $info) {
		set_time_limit(3600);
		$sql_query = "INSERT INTO point (id, lat, lng, info) 
					  VALUES (".$id.", ".$lat.", ".$lng.", '".$info."')";
		$result = mysql_query($sql_query);
		return $result;
	}
	function round_f($num, $ext){
		$tmp = (float) pow(10, $ext);
		$tmp_1 = (float) round((((float)$num)*$tmp));
		return (float)($tmp_1/$tmp);
	}
?>